// src/pages/VMDetail/VMDetail.tsx
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import {
  Card,
  Tabs,
  Button,
  Space,
  Dropdown,
  Tag,
  Descriptions,
  Progress,
  MenuProps,
} from 'antd';
import {
  PlayCircleOutlined,
  PoweroffOutlined,
  ReloadOutlined,
  MoreOutlined,
  PauseCircleOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import { useDomainStore } from '../../stores/domainStore';
import { usePolling } from '../../hooks/usePolling';
import { useNotification } from '../../hooks/useNotification';
import { domainsApi } from '../../api/domains';
import ConsoleTab from './ConsoleTab';
import HardwareTab from './HardwareTab';

const VMDetail: React.FC = () => {
  const { name } = useParams<{ name: string }>();
  const {
    selectedDomain,
    fetchDomain,
    startDomain,
    shutdownDomain,
    forceStopDomain,
    rebootDomain,
    suspendDomain,
    resumeDomain,
    deleteDomain,
    domainStats,
    updateDomainStats,
  } = useDomainStore();
  const { contextHolder, showSuccess, showError } = useNotification();
  const [activeTab, setActiveTab] = useState('overview');

  // 加载虚拟机详情
  useEffect(() => {
    if (name) {
      fetchDomain(name);
    }
  }, [name, fetchDomain]);

  // 轮询状态和统计信息
  usePolling(
    async () => {
      if (name) {
        await fetchDomain(name);
        try {
          const stats = await domainsApi.getStats(name);
          updateDomainStats(name, stats);
        } catch (error) {
          console.error('Failed to fetch stats:', error);
        }
      }
    },
    { interval: 3000, enabled: !!name }
  );

  if (!selectedDomain || !name) {
    return <div>加载中...</div>;
  }

  const stats = domainStats.get(name);

  // 操作菜单
  const menuItems: MenuProps['items'] = [
    {
      key: 'reboot',
      label: '重启',
      icon: <ReloadOutlined />,
      disabled: selectedDomain.state !== 'running',
      onClick: async () => {
        try {
          await rebootDomain(name);
          showSuccess('虚拟机重启成功');
        } catch (error) {
          showError('虚拟机重启失败');
        }
      },
    },
    {
      key: 'force-stop',
      label: '强制关机',
      icon: <PoweroffOutlined />,
      danger: true,
      disabled: selectedDomain.state === 'shutoff',
      onClick: async () => {
        try {
          await forceStopDomain(name);
          showSuccess('虚拟机已强制关机');
        } catch (error) {
          showError('强制关机失败');
        }
      },
    },
    { type: 'divider' },
    {
      key: 'delete',
      label: '删除虚拟机',
      icon: <DeleteOutlined />,
      danger: true,
      disabled: selectedDomain.state !== 'shutoff',
      onClick: async () => {
        if (window.confirm(`确定要删除虚拟机 ${name} 吗？`)) {
          try {
            await deleteDomain(name);
            showSuccess('虚拟机已删除');
            window.history.back();
          } catch (error) {
            showError('删除失败');
          }
        }
      },
    },
  ];

  // 主要操作按钮
  const renderActions = () => {
    switch (selectedDomain.state) {
      case 'shutoff':
        return (
          <Button
            type="primary"
            icon={<PlayCircleOutlined />}
            onClick={async () => {
              try {
                await startDomain(name);
                showSuccess('虚拟机启动成功');
              } catch (error) {
                showError('启动失败');
              }
            }}
          >
            启动
          </Button>
        );
      case 'running':
        return (
          <>
            <Button
              icon={<PauseCircleOutlined />}
              onClick={async () => {
                try {
                  await suspendDomain(name);
                  showSuccess('虚拟机已暂停');
                } catch (error) {
                  showError('暂停失败');
                }
              }}
            >
              暂停
            </Button>
            <Button
              danger
              icon={<PoweroffOutlined />}
              onClick={async () => {
                try {
                  await shutdownDomain(name);
                  showSuccess('虚拟机关机中...');
                } catch (error) {
                  showError('关机失败');
                }
              }}
            >
              关机
            </Button>
          </>
        );
      case 'paused':
        return (
          <Button
            type="primary"
            icon={<PlayCircleOutlined />}
            onClick={async () => {
              try {
                await resumeDomain(name);
                showSuccess('虚拟机已恢复');
              } catch (error) {
                showError('恢复失败');
              }
            }}
          >
            恢复
          </Button>
        );
      default:
        return null;
    }
  };

  // 状态标签
  const getStateTag = () => {
    const stateConfig: Record<string, { color: string; text: string }> = {
      running: { color: 'success', text: '运行中' },
      paused: { color: 'warning', text: '已暂停' },
      shutoff: { color: 'default', text: '已关机' },
      crashed: { color: 'error', text: '崩溃' },
      suspended: { color: 'processing', text: '已挂起' },
    };
    const config = stateConfig[selectedDomain.state] || {
      color: 'default',
      text: selectedDomain.state,
    };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 概览标签页
  const OverviewTab = () => (
    <div style={{ padding: '16px' }}>
      <Descriptions title="基本信息" bordered column={2}>
        <Descriptions.Item label="名称">{selectedDomain.name}</Descriptions.Item>
        <Descriptions.Item label="UUID">{selectedDomain.uuid}</Descriptions.Item>
        <Descriptions.Item label="状态">{getStateTag()}</Descriptions.Item>
        <Descriptions.Item label="自动启动">
          {selectedDomain.autostart ? '是' : '否'}
        </Descriptions.Item>
        <Descriptions.Item label="CPU">{selectedDomain.vcpus} vCPU</Descriptions.Item>
        <Descriptions.Item label="内存">
          {(selectedDomain.memory / 1024).toFixed(1)} GB / {(selectedDomain.max_memory / 1024).toFixed(1)} GB
        </Descriptions.Item>
        <Descriptions.Item label="操作系统">{selectedDomain.os_type}</Descriptions.Item>
      </Descriptions>

      {stats && selectedDomain.state === 'running' && (
        <Card title="资源使用情况" style={{ marginTop: '24px' }}>
          <div style={{ marginBottom: '16px' }}>
            <div style={{ marginBottom: '8px' }}>CPU 使用率</div>
            <Progress percent={Math.round(stats.cpu_usage)} status="active" />
          </div>
          <div style={{ marginBottom: '16px' }}>
            <div style={{ marginBottom: '8px' }}>内存使用率</div>
            <Progress
              percent={Math.round((stats.memory_usage / stats.memory_available) * 100)}
              status="active"
            />
          </div>
          <Descriptions column={2} size="small">
            <Descriptions.Item label="磁盘读取">
              {(stats.disk_read_bytes / 1024 / 1024).toFixed(2)} MB
            </Descriptions.Item>
            <Descriptions.Item label="磁盘写入">
              {(stats.disk_write_bytes / 1024 / 1024).toFixed(2)} MB
            </Descriptions.Item>
            <Descriptions.Item label="网络接收">
              {(stats.network_rx_bytes / 1024 / 1024).toFixed(2)} MB
            </Descriptions.Item>
            <Descriptions.Item label="网络发送">
              {(stats.network_tx_bytes / 1024 / 1024).toFixed(2)} MB
            </Descriptions.Item>
          </Descriptions>
        </Card>
      )}
    </div>
  );

  const tabItems = [
    {
      key: 'overview',
      label: '概览',
      children: <OverviewTab />,
    },
    {
      key: 'console',
      label: '控制台',
      children: <ConsoleTab vmName={name} />,
    },
    {
      key: 'hardware',
      label: '硬件配置',
      children: <HardwareTab domain={selectedDomain} />,
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {contextHolder}
      <Card
        title={
          <Space>
            <span style={{ fontSize: '20px', fontWeight: 'bold' }}>
              {selectedDomain.name}
            </span>
            {getStateTag()}
          </Space>
        }
        extra={
          <Space>
            {renderActions()}
            <Dropdown menu={{ items: menuItems }} trigger={['click']}>
              <Button icon={<MoreOutlined />} />
            </Dropdown>
          </Space>
        }
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab} items={tabItems} />
      </Card>
    </div>
  );
};

export default VMDetail;